/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import cn.webrx.db.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * <p>Project: jdbc202202 - DeleteServlet
 * <p>Powered by webrx On 2022-08-23 11:19:52
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@WebServlet("/del.do")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if (req.getSession().getAttribute("user") != null) {

            long id = Long.parseLong(req.getParameter("id"));
            DbUtil du = new DbUtil();
            try {
                //删除照片文件
                Connection conn = du.getConn();
                PreparedStatement pst = conn.prepareStatement("select photo from t_student where id = ?");
                pst.setLong(1, id);
                ResultSet rs = pst.executeQuery();
                rs.next();
                System.out.println();
                File file = new File(req.getServletContext().getRealPath(rs.getString(1)));
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            du.deleteById("t_student", id); //删除数据库
        }
        resp.sendRedirect("/show");
    }
}
